#!/bin/bash

IMAGE=${1}
if [[ -z "${IMAGE}" ]]; then
  echo "syntax: ${0} <container-image-name>"
  exit 1
fi

set -e
#set -x

# DOCKER_BUILDKIT is much faster, but don't enable if explicity set to 0
if [[ -z "${DOCKER_BUILDKIT}" ]]; then
    export DOCKER_BUILDKIT=1
fi

# USER isn't set e.g. on cloudbuild
if [[ -z "${USER}" ]]; then
    USER=`whoami`
    echo "USER set to ${USER}"
fi

ROOT=$(dirname "${BASH_SOURCE[0]}")

echo "Building container-to-raw helper image"
docker build -t container-to-raw ${ROOT}/images/container-to-raw

# We need to export the image to a tarfile
# The easiest way seems to be to run a dummy command, then dump the container
echo "Exporting image to tarfile"
EXPORT_NAME=container-to-raw-export-${IMAGE}
if (docker inspect --type container ${EXPORT_NAME} > /dev/null 2>&1); then
    docker rm ${EXPORT_NAME}
fi
docker run --name ${EXPORT_NAME} ${IMAGE} /bin/true

SUDO=sudo
if [[ `whoami` == 'root' ]]; then
    echo "Running as root; won't use sudo"
    SUDO=""
fi

mkdir -p workspace/
docker export ${EXPORT_NAME} > workspace/${IMAGE}.tar
#docker rm ${EXPORT_NAME}

rm -f workspace/${IMAGE}.raw

echo "Converting tarfile to raw disk"
# --security-opt apparmor:unconfined is needed for mounting volumes https://github.com/moby/moby/issues/16429
# --cap-add SYS_ADMIN is needed for mounting volumes
# /dev:/dev is for loopback device partition discovery https://github.com/moby/moby/issues/27886
${SUDO} docker run \
     --privileged=true \
     --cap-add SYS_ADMIN \
     --security-opt apparmor:unconfined \
     -v /dev:/dev \
     -v `pwd`/workspace:/workspace \
     -e DISK=/workspace/${IMAGE}.raw \
     -e SRC=/workspace/${IMAGE}.tar \
     container-to-raw /makedisk.sh 

# Clean up
rm workspace/${IMAGE}.tar

# Fix user permissions
${SUDO} chown ${USER} workspace/*


echo "Done!"
